<script lang="ts" setup name="LoginForm">
import useStore from '@/store'
import { ref, watch } from 'vue'
import router from '@/router/index'
import { useRoute } from 'vue-router'
import Message from '@/components/message'
import { useCountDown } from '@/utils/hooks'
import { useForm, useField } from 'vee-validate'
import {
  accountRule,
  passwordRule,
  isAgreeRule,
  mobileRule,
  codeRule,
} from '@/utils/validate'
const { user } = useStore()
const route = useRoute()
const active = ref<'account' | 'mobile'>('account')
const { validate, resetForm } = useForm({
  // 提供初始值的配置项, 方便登录使用
  initialValues: {
    account: 'cdshi0006',
    password: '123456',
    isAgree: true,
    mobile: '18899999991',
    code: '123456',
  },
  // 校验的规则
  validationSchema: {
    // 校验的字段方法, 只有返回return true表示校验通过, 其余return 一律都是校验失败
    account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule,
    mobile: mobileRule,
    code: codeRule,
  },
})
const { value: account, errorMessage: accountErrMsg } =
  useField<string>('account')
const { value: password, errorMessage: passwordErrMsg } =
  useField<string>('password')
const { value: isAgree, errorMessage: isAgreeErrMsg } =
  useField<boolean>('isAgree')
const {
  value: mobile,
  errorMessage: mobileErrMsg,
  validate: validMobile,
} = useField<string>('mobile')
const { value: code, errorMessage: codeErrMsg } = useField<string>('code')
// 登录
const handleLogin = async () => {
  // 1.预校验 整体预校验会校验5个字段, 拆分校验
  const res = await validate()
  // console.log(res) // valid是一个布尔值, true表示通过 false表示失败
  // if (!res.valid) return
  // 2.触发登录的action
  if (active.value === 'account') {
    if (res.errors.account || res.errors.password || res.errors.isAgree) return
    await user.loginByAccount({
      account: account.value,
      password: password.value,
    })
  } else {
    if (res.errors.mobile || res.errors.code || res.errors.isAgree) return
    await user.loginByCode({ mobile: mobile.value, code: code.value })
  }
  // console.log(route.query.redirectURL)
  // if (route.query.redirectURL) {
  //   router.push(route.query.redirectURL as string)
  // } else {
  //   router.push('/')
  // }
  router.push((route.query.redirectURL as string) || '/')
  // 提示
  Message.success('登录成功')
  // // 登录成功后跳转到首页  渲染个人信息
  //
}
// 开启侦听器, 侦听active的变化,就重置
watch(
  () => active.value,
  () => {
    resetForm()
  }
)

const mobileRef = ref<HTMLInputElement>()
// 发送验证码
const { time, start } = useCountDown()
const sendCode = async () => {
  // 禁止在倒计时期间 重复倒计时
  if (time.value > 0) return Message.warning(`请${time.value}s后发送`)
  // 1. 发送验证码之前验证手机号的合法性
  const { valid } = await validMobile()
  if (!valid) return mobileRef.value!.focus() //  自动让手机号的输入框获取焦点
  // 2. 发送验证码
  await user.getCode(mobile.value)
  // 3. 提示
  Message.success('验证码已发送')
  // 4. 开启倒计时
  start()
}
</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a
        href="javascript:;"
        v-if="active === 'mobile'"
        @click="active = 'account'"
      >
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="active = 'mobile'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <template v-if="active === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              v-model="account"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <div class="error" v-if="accountErrMsg">
            <i class="iconfont icon-warning" />{{ accountErrMsg }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
              v-model="password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <div class="error" v-if="passwordErrMsg">
            <i class="iconfont icon-warning" />{{ passwordErrMsg }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              type="text"
              placeholder="请输入手机号"
              ref="mobileRef"
              v-model="mobile"
            />
          </div>
          <div class="error" v-if="mobileErrMsg">
            <i class="iconfont icon-warning" />{{ mobileErrMsg }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="text" v-model="code" placeholder="请输入验证码" />
            <span class="code" @click="sendCode">{{
              time > 0 ? `${time}s后发送` : '发送验证码'
            }}</span>
          </div>
          <div class="error" v-if="codeErrMsg">
            <i class="iconfont icon-warning" />{{ codeErrMsg }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeErrMsg">
          <i class="iconfont icon-warning" />{{ isAgreeErrMsg }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="handleLogin">登录</a>
    </div>
    <div class="action">
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      >
        <img
          width="30"
          src="https://img0.baidu.com/it/u=3159829952,3018409437&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=613"
          alt=""
        />
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
